package com.gator.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import java.io.PrintWriter;

/**
 * @Author PABLO
 * @Date 2022/5/23 12:58
 * @Desc 异常过滤器     限流也走这个
 */
public class ErrorFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() {
        System.out.println("错误异常处理器");
        RequestContext currentContext = RequestContext.getCurrentContext();
        Throwable throwable = currentContext.getThrowable();
        currentContext.setResponseStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        currentContext.getResponse().setContentType("application/json;charset=utf-8");
        try {
            PrintWriter writer = currentContext.getResponse().getWriter();
            writer.println("出错了吧258万" + throwable.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
